﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace YinLongTool.Net.Http
{
	public class CharSetHelper
	{
		public static string HtmlDecode(string html)
		{
			return HttpUtility.HtmlDecode(html);
		}

		public static string HtmlEncode(string html)
		{
			return HttpUtility.HtmlEncode(html);
		}

		public static string UrlEncode(string str, System.Text.Encoding encoding)
		{
			return HttpUtility.UrlEncode(str, encoding);
		}

		public static string EscapedDataString(string str, System.Text.Encoding encoding)
		{
			return HttpUtility.UrlEncodeUnicode(str);
		}

		public static string UrlDeCode(string str, System.Text.Encoding encoding)
		{
			return HttpUtility.UrlDecode(str, encoding);
		}

		public static string UnicodeToChinese(string str)
		{
			Regex regex = new Regex("(?i)\\\\[uU]([0-9a-f]{4})");
			return regex.Replace(str, (Match m) => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString());
		}

		public static string StringUrlEncode(string str)
		{
			return StringUrlEncode(str, System.Text.Encoding.UTF8);
		}

		public static string StringUrlEncode(string str, System.Text.Encoding e)
		{
			if (str == null)
			{
				return null;
			}
			return System.Text.Encoding.ASCII.GetString(UrlEncodeToBytes(str, e));
		}

		private static byte[] UrlEncodeToBytes(string str, System.Text.Encoding e)
		{
			if (str == null)
			{
				return null;
			}
			byte[] bytes = e.GetBytes(str);
			return UrlEncodeBytesToBytesInternal(bytes, 0, bytes.Length, false);
		}

		private static byte[] UrlEncodeBytesToBytesInternal(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
		{
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < count; i++)
			{
				char c = (char)bytes[offset + i];
				if (c == ' ')
				{
					num++;
				}
				else if (!IsSafe(c))
				{
					num2++;
				}
			}
			if (!alwaysCreateReturnValue && num == 0 && num2 == 0)
			{
				return bytes;
			}
			byte[] array = new byte[count + num2 * 2];
			int num3 = 0;
			for (int j = 0; j < count; j++)
			{
				byte b = bytes[offset + j];
				char c2 = (char)b;
				if (IsSafe(c2))
				{
					array[num3++] = b;
					continue;
				}
				if (c2 == ' ')
				{
					array[num3++] = 43;
					continue;
				}
				array[num3++] = 37;
				array[num3++] = (byte)IntToHex((b >> 4) & 0xF);
				array[num3++] = (byte)IntToHex(b & 0xF);
			}
			return array;
		}

		private static bool IsSafe(char ch)
		{
			return false;
		}

		private static char IntToHex(int n)
		{
			if (n <= 9)
			{
				return (char)(n + 48);
			}
			return (char)(n - 10 + 65);
		}
	}
}
